import requests, hashlib, random, time

sess = requests.session()


class H5API(object):

    def __init__(self):
        self.base_url = "https://h5api.m.taobao.com/h5/mtop.taobao.datafront.invoke.auctionwalle/1.0/"
        self.headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3{}.86 Mobile Safari/537.36".format(random.randint(620, 700))
        }
        self.h5_tk = ""
        self.error_url = "https://h5api.m.taobao.com/h5/mtop.taobao.datafront.invoke.auctionwalle/1.0/?appKey=12574478&t=1619475958083&sign=2657498f64496a3c7d4f8b1cb8c2098d&api=mtop.taobao.datafront.invoke.auctionwalle&data=%7B%22dfApp%22%3A%22auctionwalle%22%2C%22dfApiName%22%3A%22auctionwalle.page.getScene%22%2C%22dfVariables%22%3A%22%7B%5C%22pageSpmb%5C%22%3A%5C%2212529781%5C%22%2C%5C%22pageSpmc%5C%22%3A%5C%22page-crowd%5C%22%2C%5C%22context%5C%22%3A%7B%7D%7D%22%2C%22dfVariablesRecover%22%3A%22%7B%7D%22%7D"

    def get_token(self):
        try:
            res = sess.get(self.error_url, headers=self.headers)
            self.h5_tk = res.cookies.get("_m_h5_tk").split("_")[0]
            print(self.h5_tk)
        except Exception as e:
            print(e)

    def get_request(self, data):
        if not self.h5_tk:
            print("没有token")
            return
        t = "{}".format(time.time() * 1000)
        str1 = self.h5_tk + "&" + t + "&12574478" + "&" + repr(data)
        sign = hashlib.md5(str1.encode(encoding="utf-8")).hexdigest()
        params = {
            "sign": sign,
            "appKey": "12574478",
            "t": t,
            "data": repr(data)
        }

        print(sess.get(self.base_url, params=params, headers=self.headers).text)


if __name__ == '__main__':
    h5api = H5API()
    h5api.get_token()
    h5api.get_request({"dfApp":"auctionwalle","dfApiName":"auctionwalle.page.getScene","dfVariables":"{\"pageSpmb\":\"12529781\",\"pageSpmc\":\"page-crowd\",\"context\":{}}","dfVariablesRecover":"{}"})
